function getArgs(search) {
    var args = {},
        query = search || location.search.substring(1),
        pairs = query.split("&");
    for (var i = 0; i<pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
        if (pos == -1) continue;
        var argname = pairs[i].substring(0, pos),
            value = pairs[i].substring(pos + 1);
        value = decodeURIComponent(value);
        args[argname] = value;
    }
    return args;
}
let args = getArgs();
let level = Number(args['level']) || 1;
document.querySelector('#title').innerHTML = 'Level - '+ level;

const neededImgNumber = level
const allItemsLength= allItems.length

const randomNumber = Math.floor(Math.random() * allItems.length)
console.log(randomNumber, allItems.length);

let pickedImg = allItems.splice(randomNumber, neededImgNumber)

// 取值超出数组长度则从0开始取剩下的部分
if(randomNumber + neededImgNumber - allItemsLength >= 0) {
  // 剩下的长度
  const remainLength = neededImgNumber - pickedImg.length
  pickedImg.push(...allItems.splice(0, remainLength))
}
const displayArray = [...pickedImg,...pickedImg].sort(_ => 0.5 - Math.random())

if(neededImgNumber > allItemsLength/2) {
  alert('level超出了图片数量！');
  window.location.href = 'all_levels.html'
}
let finded_couples_num = 0;
let container = document.querySelector('.memory-game');
let html='';
displayArray.map(function(item){
  html += '<div class="memory-card" data-framework="' + item + '">\
    <img src="images/animal/' + item + '.jpg" class="back-face" alt="'+ item +'">\
    <img src="images/font_face.jpg" class="font-face" alt="memory">\
  </div>'
})
container.innerHTML=html;

let card_item = document.querySelectorAll('.memory-card');
let card_parent = document.querySelector('.memory-game');
let body = document.body;
function setSize(){
  // if(body.offsetWidth < body.offsetHeight){
    card_item.forEach(function(dom){
      // if(neededImgNumber <= 2){
      //   dom.style.width =(0.5 * card_parent.offsetWidth - 10) + 'px';
      //   dom.style.paddingBottom = "62%";
      // }else if(neededImgNumber % 3 === 0){
      //   dom.style.width =(0.3333 * card_parent.offsetWidth - 10) + 'px';
      //   dom.style.paddingBottom = "40%";
      // }else{
        dom.style.width =(0.25 * card_parent.offsetWidth - 10) + 'px';
        dom.style.paddingBottom = "30%";
  //     }
    })
  // }else{
  //   card_item.forEach(function(dom){
  //     dom.style.width = 120 + 'px';
  //     dom.style.paddingBottom = "28%";
  //   })
  // }
}
setSize();
window.addEventListener('resize',function(){
  setSize();
})
let $success_block = document.querySelector('#success');
let $next_level_btn = document.querySelector('#next_level');
document.querySelector('#close').addEventListener('click',function(){
  $success_block.style.display = 'none';
})
$success_block.style.display = 'none';
$next_level_btn.addEventListener('click', function(e){
  e.stopPropagation();
  window.location.href = "index.html?level=" + (level + 1);
})

const cards = document.querySelectorAll('.memory-card');
cards.forEach(function(card){
  card.addEventListener('click', flipCard)
});

let hasFlippedCard = false,lockBoard = false;
let firstCard,secondCard;

function flipCard() {
  if(lockBoard) return;
  if(firstCard === this) return;
  this.classList.add('flip');
  if(!hasFlippedCard){
    hasFlippedCard = true;
    firstCard = this;
    return
  }
    secondCard = this;
    lockBoard = true;
    checkForMatch()
}

function checkForMatch(){
  firstCard.dataset.framework === secondCard.dataset.framework ? disbleCards():
  unfilpCards();
}

function disbleCards(){
  firstCard.removeEventListener('click',flipCard);
  secondCard.removeEventListener('click',flipCard);
  finded_couples_num++;
  if(finded_couples_num === neededImgNumber){
    setTimeout(function(){
      $success_block.style.display = 'block';
    },1000)
  }
  neededImgNumber >= allItemsLength/2 ? $next_level_btn.style.display = 'none' : '';
  resetCard()
};

function unfilpCards(){
  lockBoard = true;
  setTimeout(function(){
    firstCard.classList.remove('flip');
    secondCard.classList.remove('flip');
    resetCard();
  },1200)
}

function resetCard(){
  [hasFlippedCard,lockBoard] = [false,false];
  [firstCard,secondCard] = [null,null]
}

(function shuffle() {
  cards.forEach(card => {
    let ramdomPos = Math.floor(Math.random() * (displayArray.length));
    card.style.order = ramdomPos;
  });
})();

document.querySelector('#btn').addEventListener('click', function(e){
  e.stopPropagation();
  window.location.reload();
})
